package ru.niir.goodfil.db.handlers;

import org.hibernate.StatelessSession;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ConnGoodsBrandsCacheExtender extends GoodfilExtender {
    private Map<Long, Long> cache = new HashMap<Long, Long>();

    public ConnGoodsBrandsCacheExtender(Goodfil gf) {
        super(gf);
    }

    private void init() {
        String query = "select g.`Id`, gt.`IdBrand` from  Goods g, GoodTypes gt where (g.`IdGoodType` = gt.`Id`) and (gt.`IdBrand` is not null)";

        StatelessSession session = gf.getSession();
        List result = session.createSQLQuery(query).list();
        for (Object obj : result) {
            Object[] objs = (Object[]) obj;
            Long goodId = ((Number) objs[0]).longValue();
            Long brandId = ((Number) objs[1]).longValue();
            cache.put(goodId, brandId);
        }
    }

    public long getBrandIdByGoodId(long goodId) {
        if (cache.size() == 0) init();
        return cache.get(goodId);
    }
}